package com.hzsai.config;

import com.hzsai.mappersb.FilmMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * hzsai
 * 2019/8/20 16:05
 * usage:
 */
@Configuration
@MapperScan(basePackages = {"com.hzsai.mappersb"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MyBatisDSConfigB {

    @Bean(value = "sqlSessionFactory2")
    public SqlSessionFactory sqlSessionFactory2(@Qualifier(value = "sakilaDS") DataSource ds2) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds2);
        return bean.getObject();
    }

    @Bean
    @Primary
    public DataSourceTransactionManager managerDS2(@Qualifier(value = "sakilaDS") DataSource ds2) {
        return new DataSourceTransactionManager(ds2);
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2(
            @Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory
    ) throws Exception{
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}
